import { onMounted, onUnmounted, ref, readonly } from "vue";
import { debounce } from "./debounce";
import { resolvemdpathfromurl } from "./resolvemdpathfromurl";

export function usemarkdownurl(): { readonly value: string } {
    let eventname: string;
    if (process.env.PRERENDER) {
        eventname = "popstate";
    } else {
        eventname = "hashchange";
    }
    const mdurl = ref(resolvemdpathfromurl());
    const listener = debounce(() => {
        mdurl.value = resolvemdpathfromurl();
    });
    onMounted(() => {
        window.addEventListener(eventname, listener);
    });
    onUnmounted(() => {
        window.removeEventListener(eventname, listener);
        listener.cancel();
    });
    return readonly(mdurl);
}
